package com.jjb.spider.mqtt.net;

import com.jjb.spider.common.bootstaeap.AbstractBootstrapServer;
import com.jjb.spider.mqtt.handler.MqttHandler;
import com.jjb.spider.mqtt.handler.MqttNetHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class NettyContentService extends AbstractBootstrapServer implements InitializingBean, ApplicationListener<ContextClosedEvent> {

    @Value("${mqtt.port}")
    private int port;

    @Autowired
    private MqttHandler mqttHandler;


    @Value("${mqtt.channel.read.timeout: 600}")
    private int channelReadTime;



    @Override
    public void initChannelPipelineLast(ChannelPipeline channelPipeline) {
        // 设置读写空闲超时时间
        channelPipeline.addLast(new IdleStateHandler(600, 0, 0, TimeUnit.SECONDS));

        channelPipeline.addLast("encoder", MqttEncoder.INSTANCE);
        channelPipeline.addLast("decoder", new MqttDecoder());

        channelPipeline.addLast(new MqttNetHandler(this.mqttHandler));
    }

    @Override
    public int port() {
        return this.port;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.startup();
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.info("开始关闭netty容器");
        super.close();
    }
}
